package avicit.bdp.dms.oauth2.validator;

import avicit.bdp.dms.oauth2.token.OauthPasswordToken;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO
 *
 * @author xugb
 * @date 2024/4/12 15:14
 */

public abstract class AbstractOauthTokenValidator extends AbstractClientDetailsValidator {
    private static final Logger LOG = LoggerFactory.getLogger(AbstractOauthTokenValidator.class);
    protected OAuthTokenRequest tokenRequest;

    protected AbstractOauthTokenValidator(OAuthTokenRequest tokenRequest) {
        super(tokenRequest);
        this.tokenRequest = tokenRequest;
    }

    protected String grantType() {
        return this.tokenRequest.getGrantType();
    }

    protected OAuthResponse invalidGrantTypeResponse(String grantType) throws OAuthSystemException {
        return OAuthResponse.errorResponse(401).setError("invalid_grant").setErrorDescription("Invalid grant_type '" + grantType + "'").buildJSONMessage();
    }

    protected OAuthResponse invalidTrustResponse(String grantType) throws OAuthSystemException {
        return OAuthResponse.errorResponse(401).setError("invalid_grant").setErrorDescription("Invalid grant_type '" + grantType + "' with username").buildJSONMessage();
    }

    protected boolean invalidUsernamePassword() {
        String username = this.tokenRequest.getUsername();
        String password = this.tokenRequest.getPassword();
        String clientSecret = this.tokenRequest.getClientSecret();

        try {
            SecurityUtils.getSubject().login(new OauthPasswordToken(username, password, true, clientSecret));
            return false;
        } catch (Exception var5) {
            LOG.debug("Login failed by username: " + username, var5);
            return true;
        }
    }

    protected boolean invalidTrustUsername() {
        String username = this.tokenRequest.getUsername();

        try {
            SecurityUtils.getSubject().login(new OauthPasswordToken(username, username, false, ""));
            return false;
        } catch (Exception var3) {
            LOG.error("Login failed by username: " + username, var3);
            return true;
        }
    }

    protected OAuthResponse invalidUsernamePasswordResponse() throws OAuthSystemException {
        return OAuthResponse.errorResponse(400).setError("invalid_grant").setErrorDescription("Bad credentials").buildJSONMessage();
    }
}
